import React, { useEffect, useState } from "react";
import {Button,Divider,Tooltip,Badge,Spin, message,Modal,Form,Empty} from 'antd'
import {LinkOutlined,FolderAddOutlined,FormOutlined,DeleteOutlined,DownOutlined,UpOutlined,ExclamationCircleOutlined} from '@ant-design/icons'
import SubjectComponent from "components/LlxPreview/subjectComponent";
import {getThemeSubject,getLevideoSubject,pushSubjectFromAll,getPaperSubject,getBookSubject,delSubject as delSubjects,editSubjectInfoBatch,importSubjects,getSubjectInfo} from 'api/index'
import PushSubject from '../LlxPushData/subject'
import { connect } from 'react-redux'
import {setPageData,addHistoryRouter,setDictionaries} from 'redux/action'
import QuoteSubject from "components/LlxPreview/QuoteSubject";
import AddOrEditSubject from "components/AddOrEditSubject";
import EditSubject from 'components/EditSubjec'
const {confirm} = Modal


function AfterQuestions(props) {

  const {type,id,globalType,disabled} = props
  const [subjects,setSubjects] = useState([])
  const [spinning,setSpinning] = useState(true)
  const [isModalVisible,setIsModalVisible] = useState(false)
  const [isModalVisibleQuo,setIsModalVisibleQuo] = useState(false)
  const [isModalVisibleSubject,setIsModalVisibleSubject] = useState(false)
  const [isModalVisibleEditSubject,setIsModalVisibleEditSubject] = useState(false)
  const [quoteData,setQuoteData] = useState({})

  const [subjectForm] = Form.useForm();//搜索列表
  const [subjectFormNew] = Form.useForm();//搜索列表

  useEffect(()=>{
    switch(type){
      // 学习视频
      case 'LE_VIDEO':
     const getSubject1 = async()=>{
     const res1 = await getLevideoSubject(id)
       setSubjects(res1.result||[])
       setSpinning(false)
     }  
      getSubject1()
    break
    case 'IR_BOOK':
      const getSubject2 = async()=>{
      const res1 = await getBookSubject(id)
        setSubjects(res1.result||[])
        setSpinning(false)
      }  
       getSubject2()
     break
     case 'THEME':
      const getSubject3 = async()=>{
      const res1 = await getThemeSubject(id)
        setSubjects(res1.result||[])
        setSpinning(false)
      }  
       getSubject3()
     break
     case 'PAPER':
      const getSubject4 = async()=>{
      const res1 = await getPaperSubject(id)
        setSubjects(res1.result||[])
        setSpinning(false)
      }  
       getSubject4()
     break
     case 'TEST':
      const getSubject5 = async()=>{
      const res1 = await getPaperSubject(id)
        setSubjects(res1.result||[])
        setSpinning(false)
      }  
       getSubject5()
     break
    default:
      return
    }
  },[])// eslint-disable-line react-hooks/exhaustive-deps

  // 查看更多
  const setShow = (value,i) => {
    const data = JSON.parse(JSON.stringify(subjects))
    
    data.filter(i=>i.id===value.id)[0].showMore=i

    setSubjects(data)
  }
  // 从题库导入题目
  const importSubjectFrom = () => {
    setIsModalVisible(true)
  }
  // 获取导出的题目
  const importData = async(value) => {
    for(let i = 0;i<value.length;i++){
     const res = await pushSubjectFromAll({
        "globalType": globalType,
        "importId": id,
        "subjectId": value[i]
     })

    message.success(res.message)
    }
    setIsModalVisible(false)

    // 更新数据
    getInfoFn()
  }
  // 获取最新数据
  const getInfoFn = () => {
    setSpinning(true)
    switch(type){
      // 学习视频
      case 'LE_VIDEO':
     const getSubject1 = async()=>{
     const res1 = await getThemeSubject(id)
       setSubjects(res1.result||[])
       setSpinning(false)
     }  
      getSubject1()
    break
    case 'IR_BOOK':
      const getSubject2 = async()=>{
      const res1 = await getBookSubject(id)
        setSubjects(res1.result||[])
        setSpinning(false)
      }  
       getSubject2()
     break
     case 'THEME':
      const getSubject3 = async()=>{
      const res1 = await getThemeSubject(id)
        setSubjects(res1.result||[])
        setSpinning(false)
      }  
       getSubject3()
     break
     case 'PAPER':
      const getSubject4 = async()=>{
      const res1 = await getPaperSubject(id)
        setSubjects(res1.result||[])
        setSpinning(false)
      }  
       getSubject4()
     break
    default:
      return
    }
  }
  // 查看引用
  const lookQuote = (value) => {
    setQuoteData(value.referenceList)

    setIsModalVisibleQuo(true)
  }
  // 添加到题库
  const pushToAll = async(value) => {
   const res = await importSubjects({
      subjectId: [value.id],
      globalOriginType: globalType,
      importId:id
    })
      message.success(res.message)
  }
  // 编辑
  const editSubject =async(value) => {
    const res = await getSubjectInfo(value.id)
    subjectForm.setFieldsValue({
      ...res.result,
      type:[res.result.type+'',res.result.subjectType+''],
      label:res.result.labels?.map(i=>{
        return [i.labelCategoryId,i.id]
      }),
      examinationTypeId:res.result.examinationType?.map(i=>{
        return i.grammarId?i.grammarId:i.examinationTypeId
      })
    })

    if(res.result.type===5){
      const data = res.result.answerList[0]?.answer.split(' ').map(i=>{
        if(i==='A') {
          return 0
        }
        if(i==='B') {
          return 1
        }
        if(i==='C') {
          return 2
        }
        if(i==='D') {
          return 3
        }
      })
      subjectForm.setFieldsValue({
        options:res.result.options.map((i,j)=>{
          i.pictureUrlOld = res.result.options[data[j]].pictureUrl

          return i
        })
      })
    }
    setIsModalVisibleEditSubject(true)
  }
  // 移除
  const delSubject = async(value) => {

    // 需要判断是否是该素材持有


    confirm({
      title: '你确定要删除?',
      icon: <ExclamationCircleOutlined />,
      okText: '确定',
      cancelText: '取消',
       async onOk() {
      const res =  await delSubjects(value.id)
        message.success(res.message)
        getInfoFn()
      },
      onCancel() {
      },
    });

  }
  // 上移
  const goTop = async(value) => {
    if(value===0){
      message.error('你已经是第一个了,无法上移')
      return
    }
    await editSubjectInfoBatch([
      {id:subjects[value].id,sort:subjects[value].sort-1},{id:subjects[value-1].id,sort:subjects[value-1].sort+1}
    ])
    message.success('操作成功')
    getInfoFn()
  }
  // 下移
  const goBottom = async(value) => {
    if(value===subjects.length-1){
      message.error('你已经是最后一个了,无法下移')
      return
    }
    await editSubjectInfoBatch([
      {id:subjects[value].id,sort:subjects[value].sort+1},{id:subjects[value+1].id,sort:subjects[value+1].sort-1}
    ])
    message.success('操作成功')
    getInfoFn()
  }
  // 新增题目
  const addSubject = () => {
    subjectFormNew.resetFields();
    subjectFormNew.setFieldsValue({
      label:'',
      id:'',
      examinationTypeId:'',type:'',guideAudio:'',guideText:'',subjectName:'',pictureUrl:'',audioUrl:'',analysisAudio:'',analysisText:'',backgroundMusic:''
    })
    setIsModalVisibleSubject(true)
  }

  return <div className="after-questions">
      
    <div className="after-btn">
      <Button disabled={disabled} type={'primary'} size={'small'} onClick={addSubject}>自行出题</Button>
      <Button disabled={disabled} type={'primary'} size={'small'} onClick={importSubjectFrom}>从题库导入</Button>
    </div>
   
    <Spin tip="Loading..." style={{margin:'100px 0 0 0'}} spinning={spinning}>
      {
        subjects.length?<div className="subject animate__animated animate__fadeIn">

        {subjects&&subjects.length?subjects.map((i,j)=>{
          return   <div key={i.id}>
            <div style={{ width: '100%' }} className='subject-item'>
              <div className="operate-icon" style={{zIndex:99}}>
               <Tooltip onClick={()=>lookQuote(i)} title="查看引用"><LinkOutlined className="icon"/></Tooltip>

                {
                   i.externalImport?'':<>
                    <Tooltip  onClick={()=>pushToAll(i)} title="添加到题库"><FolderAddOutlined className="icon"/></Tooltip>
                   </>
                 }
               {
                 disabled?'':<>
                 {
                   i.externalImport?'':<>
                   <Tooltip  onClick={()=>editSubject(i)} title="编辑"><FormOutlined  className="icon" /></Tooltip>
                 <Tooltip  onClick={()=>delSubject(i)} title="移除"><DeleteOutlined className="icon"/></Tooltip>
                   </>
                 }
                 <Tooltip  onClick={()=>goTop(j)} title="上移"><UpOutlined  className="icon"/></Tooltip>
                 <Tooltip  onClick={()=>goBottom(j)} title="下移"><DownOutlined className="icon"/></Tooltip>
                 </>
               }
              </div>
              <SubjectComponent count={subjects.length} sort={j+1} subjectItem={i} setShow={setShow}></SubjectComponent>
            <Divider />
           </div>
          </div>
        }):''}
        </div>:<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
      }
    </Spin>

    <PushSubject globalOriginType={type==='IR_BOOK'?1:(type==='THEME'?5:'')} userName={props.userInfo.user.userName} importData={importData} dictionaries={props.dictionaries} isModalVisible={isModalVisible} setIsModalVisible={setIsModalVisible}></PushSubject>

    <QuoteSubject isModalVisible={isModalVisibleQuo}  setIsModalVisible={setIsModalVisibleQuo} quoteData={quoteData}></QuoteSubject>

    <AddOrEditSubject type={type} getInfoFn={getInfoFn} sort={subjects.length+1} globalOriginType={globalType}   paperBookId={id}  dictionaries={props.dictionaries} form={subjectFormNew} isModalVisible={isModalVisibleSubject}  setIsModalVisible={setIsModalVisibleSubject} ></AddOrEditSubject>
  
  
    <EditSubject getInfoFn={getInfoFn}  dictionaries={props.dictionaries} form={subjectForm} isModalVisible={isModalVisibleEditSubject}  setIsModalVisible={setIsModalVisibleEditSubject} ></EditSubject>
  </div>
}


// 映射方法
const mapDispatchToProps = (dispatch) => {
  return {
    addRouter: (route) => dispatch(addHistoryRouter(route)),
    setPageDataFn: (url,data) => dispatch(setPageData(url,data)),
    setDictionaries: (url,data) => dispatch(setDictionaries(url,data))
  }
}

export default connect((state)=>{
  return {tabList:state.tabList,examineStatus:state.examineStatus,userInfo:state.userInfo,dictionaries:state.dictionaries}
},mapDispatchToProps)(AfterQuestions)
